﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Linq;

namespace Helpers
{
    public static class HttpClientHelper
    {
        public static HttpClient CreateHttpClient(Config config)
        {
            HttpClientHandler httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = config.AllowAutoRedirect,
                AutomaticDecompression = config.AutomaticDecompression,
                UseCookies = config.UseCookies,
                CookieContainer = config.CookieContainer,
                Proxy = config.ProxyEndpoint == null ? null :
                new WebProxy(config.ProxyEndpoint)
                {
                    Credentials = new NetworkCredential(config.ProxyUserName, config.ProxyPassword)
                },
            };
            HttpClient httpClient = new HttpClient(httpClientHandler);
            httpClient.Timeout = config.Timeout;
            httpClient.DefaultRequestHeaders.ConnectionClose = config.ConnectionClose;
            for (int i = 0; i < config.DefaultRequestHeaders?.Count; i++)
            {
                var header = config.DefaultRequestHeaders.ElementAt(i);
                httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            return httpClient;
        }

        public class Config
        {
            /// <summary>
            /// 默认不使用代理
            /// </summary>
            public string ProxyEndpoint { get; set; } = null;
            public string ProxyUserName { get; set; } = null;
            public string ProxyPassword { get; set; } = null;
            /// <summary>
            /// 默认不重定向
            /// </summary>
            public bool AllowAutoRedirect { get; set; } = false;
            public DecompressionMethods AutomaticDecompression { get; set; } = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            /// <summary>
            /// 默认不使用cookie
            /// </summary>
            public bool UseCookies { get; set; } = false;
            public CookieContainer CookieContainer { get; set; } = null;
            /// <summary>
            /// 默认超时时间
            /// </summary>
            public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30);
            public Dictionary<string, string> DefaultRequestHeaders { get; set; } = new Dictionary<string, string> {
                { "Accept", "text/html, application/xhtml+xml, image/jxr, */*" },
                { "Accept-Encoding","gzip, deflate"},
                //{ "Connection","close"},
            };
            public bool ConnectionClose { get; set; } = true;
        }

        
    }
}
